#include "UserDataAccess.h"

// 通过邮箱注册方法 userRegisteremail
int UserDataAccess::userRegisterEmail(const QString &email, const QString &password)
{
    DbConnector dbConnector;
    QSqlQuery query(dbConnector.getDatabase());

    QString sql;

    // 检查用户是否已存在
    sql = "SELECT * FROM UserCredentials WHERE email = :email";
    query.prepare(sql);
    query.bindValue(":email", email);

    if (query.exec() && query.next())
    {
        return -1; // 用户已存在
    }

    // 插入新用户
    sql = "INSERT INTO UserCredentials (email, password) VALUES (:email, :password)";
    query.prepare(sql);
    query.bindValue(":email", email);
    query.bindValue(":password", password);

    if (!query.exec())
    {
        qDebug() << "插入新用户失败";
        return -1;
    }

    // 获取新用户的userId
    sql = "SELECT user_Id FROM UserCredentials WHERE email = :email AND password = :password";
    query.prepare(sql);
    query.bindValue(":email", email);
    query.bindValue(":password", password);

    if (!query.exec() || !query.next())
    {
        qDebug() << "查询新用户ID失败";
        return -1;
    }

    int userId = query.value(0).toInt();

    // 向UserInfo表中插入新记录，使用email作为昵称
    sql = "INSERT INTO UserInfo (user_Id, nickname) VALUES (:userId, :nickname)";
    query.prepare(sql);
    query.bindValue(":userId", userId);
    query.bindValue(":nickname", email);

    if (!query.exec())
    {
        qDebug() << "插入用户信息失败";
        return -1;
    }

    return userId;
}

// 通过邮箱登录方法  userLoginemail
int UserDataAccess::userLoginEmail(const QString &email, const QString &password)
{
    DbConnector dbConnector;
    QSqlQuery query(dbConnector.getDatabase());

    QString sql;
    sql = "SELECT user_Id FROM UserCredentials WHERE email = :email AND password = :password";
    query.prepare(sql);
    query.bindValue(":email", email);
    query.bindValue(":password", password);
    if (!query.exec())
    {
        return -1; // 数据库查询失败
    }

    if (query.next())
    {
        return query.value(0).toInt(); // 返回用户ID
    }
    else
    {
        return -1; // 用户名或密码错误
    }
}

// 通过手机注册方法  userRegisterPhone
int UserDataAccess::userRegisterPhone(const QString &phoneNumber, const QString &password)
{
    DbConnector dbConnector;
    QSqlQuery query(dbConnector.getDatabase());

    QString sql;

    // 检查用户是否已经存在
    sql = "SELECT * FROM UserCredentials WHERE phonenumber = :phonenumber";
    query.prepare(sql);
    query.bindValue(":phonenumber", phoneNumber);

    if (query.exec() && query.next())
    {
        return -1; // 用户已存在
    }

    // 插入新用户到UserCredentials表
    sql = "INSERT INTO UserCredentials (phonenumber, password) VALUES (:phonenumber, :password)";
    query.prepare(sql);
    query.bindValue(":phonenumber", phoneNumber);
    query.bindValue(":password", password);

    if (!query.exec())
    {
        return -1; // 插入失败
    }

    // 获取新用户的userId
    sql = "SELECT user_Id FROM UserCredentials WHERE phonenumber = :phonenumber AND password = :password";
    query.prepare(sql);
    query.bindValue(":phonenumber", phoneNumber);
    query.bindValue(":password", password);

    if (!query.exec() || !query.next())
    {
        return -1; // 查询userId失败
    }

    int userId = query.value(0).toInt();

    // 同时在UserInfo表中插入一条记录，使用phoneNumber作为昵称
    sql = "INSERT INTO UserInfo (user_Id, nickname) VALUES (:userId, :nickname)";
    query.prepare(sql);
    query.bindValue(":userId", userId);
    query.bindValue(":nickname", phoneNumber);

    if (!query.exec())
    {
        return -1; // 在UserInfo表中插入失败
    }

    return userId;
}

// 通过手机登录方法  userLoginPhone
int UserDataAccess::userLoginPhone(const QString &phoneNumber, const QString &password)
{
    DbConnector dbConnector;
    QSqlQuery query(dbConnector.getDatabase());

    QString sql;
    sql = "SELECT user_Id FROM UserCredentials WHERE phonenumber = :phonenumber AND password = :password";
    query.prepare(sql);
    query.bindValue(":phonenumber", phoneNumber);
    query.bindValue(":password", password);

    if (!query.exec())
    {
        return -1; // 数据库查询失败
    }

    // qDebug() << "Executed SQL:" << query.lastQuery();

    if (query.next())
    {
        return query.value(0).toInt(); // 返回用户ID
    }
    else
    {
        return -1; // 用户名或密码错误1
    }
}

// 修改密码方法  changePassword
bool UserDataAccess::changePassword(const QString &userId, const QString &newPassword)
{
    DbConnector dbConnector;
    QSqlQuery query(dbConnector.getDatabase());

    QString sql;
    sql = "UPDATE UserCredentials SET Password = :newPassword WHERE userId = :userId";
    query.prepare(sql);
    query.bindValue(":newPassword", newPassword);
    query.bindValue(":userId", userId.toLongLong());

    if (!query.exec())
    {
        qDebug() << "更改密码失败：" << query.lastError().text();
        return false;
    }

    return true;
}

// 注销用户方法 deleteAccount
bool UserDataAccess::deleteAccount(const QString &userId)
{
    DbConnector dbConnector;
    QSqlQuery query(dbConnector.getDatabase());

    const QString sql = "DELETE FROM UserCredentials WHERE userId = :userId";
    query.prepare(sql);
    query.bindValue(":userId", userId.toLongLong());

    if (!query.exec())
    {
        qDebug() << "删除账户失败：" << query.lastError().text();
        return false;
    }

    return true;
}

// 个人信息显示    getUserInfo
UserInfo UserDataAccess::getUserInfo(const int &userId)
{
    DbConnector dbConnector;
    QSqlQuery query(dbConnector.getDatabase());

    QString sql;
    sql = "SELECT nickname, gender, email, signature FROM UserInfo WHERE user_id = :userId";
    query.prepare(sql);
    query.addBindValue(userId);

    if (!query.exec())
    {
        qDebug() << "查询用户信息失败：" << query.lastError().text();
        return UserInfo(); // 返回默认构造的 UserInfo 对象
    }

    UserInfo userInfo;

    if (query.next())
    {
        userInfo.nickname = query.value("nickname").toString();
        userInfo.gender = query.value("gender").toString();
        userInfo.email = query.value("email").toString();
        userInfo.signature = query.value("signature").toString();
    }
    else
    {
        qDebug() << "没有找到用户信息。";
    }

    return userInfo;
}
// 修改个人信息  updateUserInfo
bool UserDataAccess::updateUserInfo(const int &userId, const QString &email, const QString &nickname, const QString &gender, const QString &signature)
{
    DbConnector dbConnector;
    QSqlQuery query(dbConnector.getDatabase());

    // 构建 SET 子句
    QString setClause;
    if (!nickname.isEmpty())
    {
        setClause += "nickname = :nickname";
    }
    if (!gender.isEmpty())
    {
        if (!setClause.isEmpty())
        {
            setClause += ", ";
        }
        setClause += "gender = :gender";
    }
    if (!email.isEmpty())
    {
        if (!setClause.isEmpty())
        {
            setClause += ", ";
        }
        setClause += "email = :email";
    }
    if (!signature.isEmpty())
    {
        if (!setClause.isEmpty())
        {
            setClause += ", ";
        }
        setClause += "signature = :signature";
    }

    // 如果没有任何字段需要更新，则直接返回
    if (setClause.isEmpty())
    {
        return true; // 没有需要更新的字段
    }

    // 准备 SQL 语句
    const QString sql = "UPDATE UserInfo SET " + setClause + " WHERE user_id = :userId";
    query.prepare(sql);

    // 绑定参数
    if (!nickname.isEmpty())
    {
        query.bindValue(":nickname", nickname);
    }
    if (!gender.isEmpty())
    {
        query.bindValue(":gender", gender);
    }
    if (!email.isEmpty())
    {
        query.bindValue(":email", email);
    }
    if (!signature.isEmpty())
    {
        query.bindValue(":signature", signature);
    }
    query.bindValue(":userId", userId);

    if (!query.exec())
    {
        qDebug() << "更新用户信息失败：" << query.lastError().text();
        return false;
    }

    return true;
}

bool UserDataAccess::addUserImage(const int &userId, const QByteArray &imageData)
{
    return FileConnector::addUserImage(userId, imageData);
}

QByteArray UserDataAccess::getUserImage(const int &userId)
{
    return FileConnector::getUserImage(userId);
}
